from django.shortcuts import render
from django.shortcuts import HttpResponse
import json, time
from db.mydb import MyDBConnection
from db.dao.education_logs import Education_logs
from db.utils.dfutils import load_json_to_object
from db.utils.logutils import LogUtils


def education_logs_index(request):
    current = 1  # 如果用户不提供，默认看第一页
    pagesize = 5  # 如果用户不提供，默认每页5条
    if request.method == 'GET':  # 大小写
        myDBConnection = MyDBConnection()
        current = request.GET.get("current")
        pagesize = request.GET.get("pagesize")
        print(f'1111 {request.GET.get("current")}')
        offset = (int(current) - 1) * int(pagesize)  # 计算每页的第一条编号
        education_logs_rs_json = myDBConnection.fetch_data_by_sql(
            f"select * from education_logs limit {offset},{pagesize}")
        msg = f'现在查看的是第{current}页，每页大小{pagesize}'
        print(education_logs_rs_json)
        code = 200
        rep_json = {"code": code, "msg": msg, "education_logs_rs": education_logs_rs_json}
        print(request.GET.get('json'))
        print("------------------------------")
    if bool(request.GET.get('json')) == True:
        return HttpResponse(json.dumps(rep_json), content_type="application/json")
    else:
        return render(request, "education_logs/index.html", rep_json)


def education_logs_add(request):
    # p_id = request.POST.get("p_id")
    # p_name = request.POST.get("p_name")
    data = request.body.decode("utf-8")
    print(type(data))
    myDBConnection = MyDBConnection()
    education_logs_json_obj = json.loads(data)
    print(education_logs_json_obj)
    education_logs = load_json_to_object(education_logs_json_obj, Education_logs())
    print(type(education_logs))
    myDBConnection.insert_entity(education_logs)
    ename = education_logs.e_name
    print(ename)

    # ------------日志记录开始 ，使用自定义日志记录器LogUtils.log----------
    # path_name = '/usr/ftp/logs/education_logs/'
    path_name = 'd:log'

    current_time = time.localtime(time.time())
    current_time_str = time.strftime('%Y-%m-%d', current_time)  # 参数2为格式化字符串
    print(current_time_str)
    file_name = current_time_str + '_education_logs.log'
    LogUtils.log(path_name, file_name, education_logs.format_str())

    msg = f"{ename}球员添加成功"
    code = 200
    rep_json = {"code": code, "msg": msg}
    return HttpResponse(json.dumps(rep_json), content_type="application/json")


